﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Npgsql;
using frmPrincipalTestes;

namespace frmPrincipal
{
    public partial class frmCadProdutos : Form
    {
        private StandardDBConnection standardDBConnection = new StandardDBConnection();
        private bool isInclusion;

        public frmCadProdutos()
        {
            InitializeComponent();
        }

        //Funções Form
        private void frmCadProdutos_Load(object sender, EventArgs e)
        {
            
        }
        private void frmCadProdutos_Close(object sender, EventArgs e)
        {
            standardDBConnection.cnn.Close();
            standardDBConnection.cnn.Dispose();
        }

        //Funções Auxiliares
        private void CleanFieldsData()
        {
            txtFxEtaria.Text = "";
            txtMarca.Text = "";
            txtNome.Text = "";
            txtPreco.Text = "";
            txtAmount.Text = "";
        }
        private void CleanFields(){
            CleanFieldsData();
            btnDelete.Enabled = false;
            txtCodigo.Text = "";
            txtSearchByCode.Text = "";
            txtSearchByCode.Focus();
        }
        private bool IsFieldsFilled()
        {

            bool bPreenchido = true;

            if (txtNome.Text.Trim() == "")
            {
                txtNome.BackColor = Color.LightBlue;
                bPreenchido = false;
            }
            else
                txtNome.BackColor = Color.White;

            if (txtMarca.Text.Trim() == "")
            {
                txtMarca.BackColor = Color.LightBlue;
                bPreenchido = false;
            }
            else
                txtMarca.BackColor = Color.White;

            if (txtAmount.Text.Trim() == "")
            {
                txtAmount.BackColor = Color.LightBlue;
                bPreenchido = false;
            }
            else
                txtAmount.BackColor = Color.White;

            if (txtPreco.Text.Trim() == "")
            {
                txtPreco.BackColor = Color.LightBlue;
                bPreenchido = false;
            }
            else
                txtPreco.BackColor = Color.White;

            if (txtFxEtaria.Text.Trim() == "")
            {
                txtFxEtaria.BackColor = Color.LightBlue;
                bPreenchido = false;
            }
            else
                txtFxEtaria.BackColor = Color.White;

            return (bPreenchido);
        }

        //Pesquisar Produtos
        private void SearchProduct()
        {
            NpgsqlCommand sqlCommand = new NpgsqlCommand();
            NpgsqlDataReader databaseDataReader;

            string sqlCommandText, auxstring;
            int auxcodigo;

            if (!Testes.ValidCode(txtSearchByCode.Text))
            {
                MessageBox.Show("Forneça um código válido!", "Cadastro de Produtos", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            this.Cursor = Cursors.WaitCursor;

            sqlCommandText = "SELECT * FROM produto WHERE cod_prod = " + txtSearchByCode.Text;
            sqlCommand.CommandType = CommandType.Text;
            sqlCommand.Connection = standardDBConnection.cnn;
            sqlCommand.CommandText = sqlCommandText;
            databaseDataReader = sqlCommand.ExecuteReader();

            if (!databaseDataReader.HasRows)
            {
                isInclusion = true;
                MessageBox.Show("Não Encontrado. Portanto será utilizado o próximo código disponível para cadastro.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                databaseDataReader.Close();
                databaseDataReader.Dispose();
                sqlCommand.Dispose();
                sqlCommand.CommandType = CommandType.Text;
                standardDBConnection.cnn.Close();
                standardDBConnection.cnn.Open();
                sqlCommand.Connection = standardDBConnection.cnn;
                sqlCommand.CommandText = "SELECT last_value FROM produto_cod_prod_seq ";
                databaseDataReader = sqlCommand.ExecuteReader();
                databaseDataReader.Read();
                auxstring = databaseDataReader["last_value"].ToString();
                auxcodigo = Convert.ToInt32(auxstring) + 1;
                CleanFieldsData();
                txtSearchByCode.Text = auxcodigo.ToString();
                txtCodigo.Text = auxcodigo.ToString();
                btnDelete.Enabled = false;
            }

            else
            {
                isInclusion = false;
                databaseDataReader.Read();
                txtCodigo.Text = databaseDataReader["cod_prod"].ToString();
                txtNome.Text = databaseDataReader["nome_prod"].ToString();
                txtMarca.Text = databaseDataReader["marca"].ToString();
                txtAmount.Text = databaseDataReader["qtd_estoque"].ToString();
                txtPreco.Text = databaseDataReader["preco_venda"].ToString();
                txtFxEtaria.Text = databaseDataReader["fxetaria"].ToString();
                btnDelete.Enabled = true;
            }

            databaseDataReader.Close();
            databaseDataReader.Dispose();
            sqlCommand.Dispose();
            this.Cursor = Cursors.Default;
        }
        private void btnSearch_Click(object sender, EventArgs e)
        {
            SearchProduct();
        }
        private void txtSearch_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode == Keys.Enter)
                SearchProduct();
        }

        //Botões
        private void btnNew_Click(object sender, EventArgs e)
        {
            CleanFields();
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            NpgsqlCommand sqlCommand = new NpgsqlCommand();
            string sqlCommandText;

            if (!IsFieldsFilled())
            {
                MessageBox.Show("Preencha os campos destacados!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            this.Cursor = Cursors.WaitCursor;

            if (isInclusion)
            {

                sqlCommandText = "INSERT INTO produto (nome_prod, marca, qtd_estoque, preco_venda, fxetaria) ";
                sqlCommandText = sqlCommandText + "values('" + txtNome.Text + "',";
                sqlCommandText = sqlCommandText + "'" + txtMarca.Text + "',";
                sqlCommandText = sqlCommandText + "'" + txtAmount.Text + "',";
                sqlCommandText = sqlCommandText + "'" + txtPreco.Text + "',";
                sqlCommandText = sqlCommandText + "'" + txtFxEtaria.Text + "')";
            }
            else
            {
                sqlCommandText = "update produto ";
                sqlCommandText = sqlCommandText + "set nome_prod = '" + txtNome.Text + "',";
                sqlCommandText = sqlCommandText + " marca = '" + txtMarca.Text + "',";
                sqlCommandText = sqlCommandText + " qtd_estoque = '" + txtAmount.Text + "',";
                sqlCommandText = sqlCommandText + " preco_venda = '" + txtPreco.Text + "',";
                sqlCommandText = sqlCommandText + " fxetaria = '" + txtFxEtaria.Text + "'";
                sqlCommandText = sqlCommandText + " WHERE cod_prod = " + txtCodigo.Text;


            }

            sqlCommand.CommandType = CommandType.Text;
            sqlCommand.Connection = standardDBConnection.cnn;
            sqlCommand.CommandText = sqlCommandText;
            sqlCommand.ExecuteNonQuery();

            MessageBox.Show("Gravação Efetuada com Sucesso!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            CleanFields();
            sqlCommand.Dispose();
            this.Cursor = Cursors.Default;
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            NpgsqlCommand sqlCommand = new NpgsqlCommand();
            string sqlCommandText;
            DialogResult resp;

            resp = MessageBox.Show("Confirma a exclusão do registro?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (resp == DialogResult.Yes)
            {

                this.Cursor = Cursors.WaitCursor;

                sqlCommand.CommandType = CommandType.Text;
                sqlCommand.Connection = standardDBConnection.cnn;
                sqlCommandText = "DELETE FROM produto WHERE cod_prod = " + txtCodigo.Text;
                sqlCommand.CommandText = sqlCommandText;
                sqlCommand.ExecuteNonQuery();

                MessageBox.Show("Exclusão efetuada com sucesso!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);

                CleanFields();
                sqlCommand.Dispose();

                this.Cursor = Cursors.Default;
            }
        }
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

    }
}

